<template>
  <n-drawer
    v-model:show="showModal"
    width="50%"
    :trap-focus="false"
    :block-scroll="false"
    to=".drawer_container"
    placement="left"
    :on-mask-click="closedDrawer"
    :on-esc="closedDrawer"
  >
    <n-drawer-content>
      <template #header>分配角色</template>
      <n-alert class="mb-3" :title="userInfo.nickName">
        <template #icon>
          <Icon icon="fluent:diversity-20-filled" />
        </template>
        <p>登录账号：{{ userInfo.userName }}</p>
      </n-alert>
      <n-form ref="formRef" :model="form" :rules="rules">
        <n-form-item label="角色" path="selectedRoles">
          <n-checkbox-group v-model:value="form.selectedRoles" class="flex-col">
            <n-checkbox
              v-for="item in rolesOptions"
              :key="item.roleId"
              :value="item.roleId"
              :label="item.roleName"
              class="mt-2"
            />
          </n-checkbox-group>
        </n-form-item>
      </n-form>
      <template #footer>
        <n-button class="mr-3" @click="closedDrawer">取消</n-button>
        <n-button type="primary" @click="save">确定</n-button>
      </template>
    </n-drawer-content>
  </n-drawer>
</template>
<script setup lang="ts">
import { getAuthRole, updateAuthRole } from '@/service/api/system/user';
import { Icon } from '@iconify/vue';

const rolesOptions = ref();
const userInfo = ref<User.ListItem | any>({});

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  userId: {
    type: Number,
    default: 0
  }
});
const showModal = computed(() => props.visible);
const form = reactive({
  selectedRoles: []
});
const rules = {
  selectedRoles: {
    required: true,
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    validator(_rule: any, value: []) {
      if (!value.length) return new Error('请选择角色');
      return true;
    },
    trigger: 'change'
  }
};

// 获取角色列表
const getAuthRoleFun = async () => {
  if (!props.userId) return;
  const { data } = await getAuthRole(props.userId);
  userInfo.value = data!.user;
  rolesOptions.value = data!.roles;
  form.selectedRoles = rolesOptions.value.filter((i: any) => Boolean(i.flag)).map((k: any) => k.roleId);
};

watch([() => props.visible, () => props.userId], ([visibleVal, userIdVal]) => {
  if (visibleVal && userIdVal) getAuthRoleFun();
});

// 关闭
const emits = defineEmits(['closed']);
const closedDrawer = () => {
  emits('closed');
};
// 保存
const formRef = ref();
const save = () => {
  formRef.value?.validate((errors: any) => {
    if (!errors) {
      updateAuthRole({ userId: props.userId, roleIds: form.selectedRoles.join() }).then(() => {
        window.$message?.success('角色分配成功');
        closedDrawer();
      });
    } else {
      console.log(errors);
    }
  });
};
</script>
